<?php
include_once '../includes/common.php';
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;

@header('Content-Type: application/json; charset=UTF-8');

if($act=='cloud_auth') {//云端添加授权
    if($conf['cloud_api_open']!=1)exit('{"code":-1,"msg":"未开启云端API服务！"}');
    $proid = intval($_GET['proid']);
    $name = daddslashes($_GET['name']);
    $qq = daddslashes($_GET['qq']);
    $url = daddslashes($_GET['url']);
    $key = daddslashes($_GET['key']);
    $ip = daddslashes($_GET['ip']);
    $keyrow = $DB->get_row("SELECT * FROM authguao_user WHERE api_key='$key' limit 1");
    $program = $DB->get_row("SELECT * FROM authguao_program WHERE id='$proid' limit 1");
    $qqrow=$DB->get_row("SELECT * FROM authguao_site WHERE proid='$proid' and qq='$qq' limit 1");
    $urlrow=$DB->get_row("SELECT * FROM authguao_site WHERE proid='$proid' and url='$url' limit 1");
    if(!$urlrow){
        $urlrow = $DB->get_row("SELECT * FROM authguao_site WHERE proid='$proid' and url='*.".get_host($url)."' limit 1");
    }
    if ($conf['api_key'] == $key) {
        $uid=1;
        if ($key != $conf['api_key']) {
            $result=array("code"=>-1,"msg"=>'API对接密钥错误！');
            exit(json_encode($result));
        } else if (in_array($ip,explode(",",$conf['api_iplist']))) {
            $result=array("code"=>-1,"msg"=>'该服务器IP不在白名单内！');
            exit(json_encode($result));
        }
    } else {
        $uid=$keyrow['uid'];
        if (!$keyrow) {
            $result=array("code"=>-1,"msg"=>'API对接密钥错误！');
            exit(json_encode($result));
        } else if ($keyrow['status'] == 0) {
            $result=array("code"=>-1,"msg"=>'API对接密钥无法使用！');
            exit(json_encode($result));
        } else if (in_array($ip,explode(",",$keyrow['api_iplist']))) {
            $result=array("code"=>-1,"msg"=>'该服务器IP不在白名单内！');
            exit(json_encode($result));
        }
        if ($keyrow['power'] < 3) {
            if ($keyrow['power'] == 2) {
                $money=$program['sqprice3'];
            }elseif ($keyrow['power'] == 1) {
                $money=$program['sqprice2'];
            }else{
                $money=$program['sqprice'];
            }
        }
        if ($keyrow['power'] < 3) {
            if ($keyrow['rmb'] < $money) {
                $result=array("code"=>-1,"msg"=>'对接账户余额不足，购买程序：'.$program['name'].'的授权还差' . ($money - $keyrow['rmb']) . '元');
                exit(json_encode($result));
            }
        }
    }
    if (!$proid) {
        $result=array("code"=>-1,"msg"=>'程序识别错误！');
    } else if (!$name) {
        $result=array("code"=>-1,"msg"=>'站点名称不能为空！');
    } else if (!$qq) {
        $result=array("code"=>-1,"msg"=>'QQ不能为空！');
    } else if (!$url) {
        $result=array("code"=>-1,"msg"=>'域名不能为空！');
    } else if (strlen($qq) < 5 || !preg_match('/^[0-9]+$/',$qq)) {
        $result=array("code"=>-1,"msg"=>'请输入正确的QQ！');
    } else if (strexists($url,"http://")) {
        $result = array("code"=>-1,"msg"=>"域名无需输入http://");
    } else if (!strexists($url,".")){
        $result = array("code"=>-1,"msg"=>"域名格式疑似不正确");
    } else if (!$program) {
        $result=array("code"=>-1,"msg"=>'该程序不存在，请联络管理员！');
    } else if ($urlrow){
        $result=array("code"=>-1,"msg"=>'该程序中，授权平台已存在该域名授权！');
    } else {
        if ($qqrow && $program['ipauth'] == 0) {
            $sign = $qqrow['sign'];
            $authcode = $qqrow['authcode'];
        } else {
            $signrow = $DB->get_row("SELECT * FROM authguao_site WHERE 1 order by sign desc limit 1");
            $sign = $signrow['sign']+1;
            $authcode = md5(random(32).$qq);
        }
        if($conf['auth_time_type']==2){
            $endtime=date('Y-m-d', strtotime('+'.$conf['auth_time'].' years'));
        }elseif($conf['auth_time_type']==1){
            $endtime=date('Y-m-d', strtotime('+'.$conf['auth_time'].' months'));
        }else{
            $endtime=date('Y-m-d', strtotime('+'.$conf['auth_time'].' days'));
        }
        $sql = "insert into `authguao_site` (`uid`,`proid`,`name`,`qq`,`url`,`date`,`authcode`,`active`,`sign`,`endtime`) values ('".$uid."','".$proid."','".$name."','".$qq."','".$url."','".$date."','".$authcode."','1','".$sign."','".$endtime."')";
        if ($DB->query($sql)) {
            if ($conf['api_key'] != $key && $keyrow['power'] < 3) {
            $DB->query("update `authguao_user` set `rmb`=`rmb`-{$money} where `uid`='{$keyrow['uid']}'");
            addPointRecord($keyrow['uid'], $money, '消费', 'API云端添加程序：'.$program['name'].'的授权，扣除'.$money.'元！剩余'.($userrow['rmb']-$money).'元');
            }
            $result=array("code"=>0,"msg"=>'添加'.$program['name'].'程序授权成功！');
        } else {
            $result=array("code"=>-1,"msg"=>'添加'.$program['name'].'程序授权失败！'.$DB->error());
        }
    }
}elseif($act=='cloud_user') {//云端添加用户
    if($conf['cloud_api_open']!=1)exit('{"code":-1,"msg":"未开启云端API服务！"}');
    $proid = intval($_GET['proid']);
    $power = intval($_GET['power']);
    $user = addslashes($_GET['user']);
    $pwd = addslashes($_GET['pwd']);
    $qq = addslashes($_GET['qq']);
    $email = addslashes($_GET['email']);
    $key = daddslashes($_GET['key']);
    $ip = daddslashes($_GET['ip']);
    $keyrow = $DB->get_row("SELECT * FROM authguao_user WHERE api_key='$key' limit 1");
    $program = $DB->get_row("SELECT * FROM authguao_program WHERE id='".$keyrow['proid']."' limit 1");
    if ($conf['api_key'] == $key) {
        $uid=1;
        if ($key != $conf['api_key']) {
            $result=array("code"=>-1,"msg"=>'API对接密钥错误！');
            exit(json_encode($result));
        } else if (in_array($ip,explode(",",$conf['api_iplist']))) {
            $result=array("code"=>-1,"msg"=>'该服务器IP不在白名单内！');
            exit(json_encode($result));
        }
    } else {
        if ($keyrow['power'] < 3) {
            if ($power == 3) {
                $money=$conf['qnprice'];
            }elseif ($power == 2) {
                $money=$program['cgprice'];
            }elseif ($power == 1) {
                if ($keyrow['power'] == 2) {
                    $money=$program['sqsprice2'];
                }else{
                    $money=$program['sqsprice'];
                }
            }
        }
        $uid=$keyrow['uid'];
        if ($power == 1) {
            $pname = '授权商';
        } else if ($power == 2) {
            $pname = '超级管理员';
        }
        if (!$keyrow) {
            $result=array("code"=>-1,"msg"=>'API对接密钥错误！');
            exit(json_encode($result));
        } else if ($keyrow['status'] == 0) {
            $result=array("code"=>-1,"msg"=>'API对接密钥无法使用！');
            exit(json_encode($result));
        } else if (in_array($ip,explode(",",$keyrow['api_iplist']))) {
            $result=array("code"=>-1,"msg"=>'该服务器IP不在白名单内！');
            exit(json_encode($result));
        } else if ($power >= $keyrow['power']) {
            $result=array("code"=>-1,"msg"=>'你的权限不足无法添加('.$pname.')！');
            exit(json_encode($result));
        }
        if ($keyrow['power'] < 3) {
            if ($keyrow['rmb'] < $money) {
                $result=array("code"=>-1,"msg"=>'对接账户余额不足，购买程序：'.$program['name'].'的'.$pname.'还差' . ($money - $keyrow['rmb']) . '元');
                exit(json_encode($result));
            }
        }
    }
    if ($power < 3) {
        if (!$program) {
            $result=array("code"=>-1,"msg"=>'该程序不存在，请联络管理员！');
            exit(json_encode($result));
        }
    }
    if (!$user) {
        $result=array("code"=>-1,"msg"=>'账号不能为空！');
    } else if ($power==0) {
        $result=array("code"=>-1,"msg"=>'普通用户无法对接！');
    } else if (!$pwd) {
        $result=array("code"=>-1,"msg"=>'密码不能为空！');
    } else if (!$qq) {
        $result=array("code"=>-1,"msg"=>'QQ不能为空！');
    } else if (!$email) {
        $result=array("code"=>-1,"msg"=>'邮箱号不能为空！');
    } else if (!preg_match('/^[a-zA-Z0-9]+$/',$user)) {
        $result=array("code"=>-1,"msg"=>'用户名只能为英文或数字！');
    } else if ($DB->get_row("SELECT * FROM authguao_user WHERE user='{$user}' limit 1")) {
        $result=array("code"=>-1,"msg"=>'用户名已存在！');
    } else if ($pwd == $user) {
        $result=array("code"=>-1,"msg"=>'账号密码不能相同！');
    } else if ($pwd == $email) {
        $result=array("code"=>-1,"msg"=>'密码不能和邮箱相同！');
    } else if (strlen($qq) < 5 || !preg_match('/^[0-9]+$/',$qq)) {
        $result=array("code"=>-1,"msg"=>'请输入正确的QQ！');
    } else if(!preg_match('/^[A-z0-9._-]+@[A-z0-9._-]+\.[A-z0-9._-]+$/', $email)){
        $result=array("code"=>-1,"msg"=>'请输入正确的邮箱！');
    } else if ($DB->get_row("SELECT * FROM authguao_user WHERE qq='{$qq}' limit 1")) {
        $result=array("code"=>-1,"msg"=>'QQ已存在！');
    } else if ($DB->get_row("SELECT * FROM authguao_user WHERE email='{$email}' limit 1")) {
        $result=array("code"=>-1,"msg"=>'邮箱号已存在！');
    } else {
        if ($power == 1) {
            $power_name = '授权商';
            $pro_name = '</br>程序：'.$program['name'];
            $proid = intval($keyrow['proid']);
        } else if ($power == 2) {
            $power_name = '超级管理员';
            $pro_name = '</br>程序：'.$program['name'];
            $proid = intval($keyrow['proid']);
        } else if ($power == 3) {
            $power_name = '全能管理员';
            $proid = '';
        }
        $sql = "insert into `authguao_user` (`upuid`,`power`,`proid`,`user`,`pwd`,`rmb`,`qq`,`email`,`invitecode`,`addtime`,`status`) values ('" . $uid . "','" . $power . "','" . $proid . "','" . $user . "','" . $pwd . "','0.00','" . $qq . "','" . $email . "','" . random(8) . "','" . $date . "','1')";
        if ($DB->query($sql)) {
            if ($conf['api_key'] != $key && $keyrow['power'] < 3) {
            $DB->query("update `authguao_user` set `rmb`=`rmb`-{$money} where `uid`='{$keyrow['uid']}'");
            addPointRecord($keyrow['uid'], $money, '消费', 'API云端添加'.$power_name.'，扣除'.$money.'元！剩余'.($userrow['rmb']-$money).'元');
            }
            $result=array("code"=>0,"msg"=>'添加'.$power_name.'成功！'.$pro_name);
        } else {
            $result=array("code"=>-1,"msg"=>'添加'.$power_name.'失败！'.$pro_name.$DB->error());
        }
    }
}elseif($act=='cloud_authedit') {
    if ($conf["apiauth_open"] == 0)exit('{"code":-1,"msg":"该站点已关闭API授权功能！"}');
    $token = daddslashes($_GET['token']);
    $url = daddslashes($_GET['url']);
    $siterow = $DB->get_row("SELECT * FROM authguao_site WHERE token='$token' limit 1");
    if (!$siterow || empty($siterow['token']) || $token != $siterow['token']) {
        $result=array("code"=>-1,"msg"=>'接口TOKEN验证失败！');
    } else if ($siterow['url'] != $url) {
        $row=$DB->get_row("SELECT * FROM authguao_site WHERE proid='{$siterow['proid']}' and url='{$url}' limit 1");
        if ($row){
            $result=array("code"=>-1,"msg"=>'该程序中已存在该授权域名！');
        }
    }else{
        $sql = "update authguao_site set url='".$url."' where id='".$siterow['id']."'";
        if($DB->query($sql)){
            $result = array("code"=>1,"msg"=>'远程更换授权成功！');
        } else {
            $result = array("code"=>-1,"msg"=>'远程更换授权失败！'.$DB->error());
        }
    }
}else {
    $result=array("code"=>-5,"msg"=>"No Act!");
}
echo json_encode($result);
$DB->close();
?>